package com.woniu.liuzhougov.fileManage.controller;

import com.sun.org.apache.xpath.internal.operations.Bool;
import com.woniu.liuzhougov.authorityControl.constant.UserConstant;
import com.woniu.liuzhougov.authorityControl.pojo.User;
import com.woniu.liuzhougov.common.utils.Result;
import com.woniu.liuzhougov.fileManage.constant.SysConstant;
import com.woniu.liuzhougov.fileManage.pojo.FileData;
import com.woniu.liuzhougov.fileManage.pojo.FileType;
import com.woniu.liuzhougov.fileManage.service.FileService;
import com.woniu.liuzhougov.fileManage.service.FileTypeService;
import com.woniu.liuzhougov.fileManage.util.GetServerRealPathUnit;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

/**
 * @description: 文件管理
 * @author: Arvin
 * @create: 2019-04-19 17:52
 **/

@Controller
@RequestMapping("fileoper")
public class FileManageController {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileTypeService fileTypeService;

    @Value("${upload.path}")
    private String filePath;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws IOException
     * @throws IllegalStateException
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file, HttpSession session,HttpServletRequest request) throws IOException,IllegalStateException {
        System.out.println("upload:::=================");
        //路径
        //String filePath = request.getSession().getServletContext().getRealPath("/upload");
        //String filePath = GetServerRealPathUnit.getPath("/upload/");

        System.out.println("路径："+filePath);

        //文件名uuid
        String filename = file.getOriginalFilename();
        String filenameUUID = UUID.randomUUID().toString()+","+filename;

        FileData fileData = SysConstant.getFileData();

        Boolean SaveStatus = saveToLocal(file,filenameUUID,filePath);

        Boolean DBstatus = saveToDB(filePath,fileData,file,filenameUUID,session);

        System.out.println(SaveStatus+"和"+DBstatus);

        if (SaveStatus && DBstatus){
            //System.out.println("上传成功");
            SysConstant.code = 200;
            return Result.success(200,"上传成功");
        }else {
            //System.out.println("上传失败");
            SysConstant.code = 500;
            return  Result.error(500,"上传失败");
        }
    }

    private Boolean saveToDB(String filePath, FileData fileData, MultipartFile file, String filenameUUID, HttpSession session) {

        long fileSize = file.getSize(); //文件大小
        if (fileSize > 1024 && fileSize <(1024*1024)){
            fileSize = fileSize/1024;
            fileData.setFileSize(fileSize+"KB");
        }else if (fileSize < 1024){
            fileData.setFileSize("1KB");
        }else {
            fileSize = fileSize/(1024*1024);
            fileData.setFileSize(fileSize+"MB");
        }
        fileData.setFileName(filenameUUID);
        fileData.setFileUrl(filePath);  //SysConstant.path
        User user = (User) session.getAttribute(UserConstant.CURRENT_USER);
        fileData.setFileLoaderId(user.getUserId());    //登录用户id

        //System.out.println(fileData.toString());
        if (fileService.uploadFile(fileData)>0){
            return true;
        }
        return false;
    }

    private Boolean saveToLocal(MultipartFile file,String filenameUUID,String filePath) {
        String filename =file.getOriginalFilename();
        String path = filePath;   //SysConstant.path;
        //文件夹判断
        File filepackage = new File(filePath);
        if (!filepackage.exists()){
            filepackage.mkdirs();
        }
        //文件防重名 File.separator用于区分windows下的/
        path = path+File.separator+filenameUUID;

        //OutputStream outputStream = new FileOutputStream();

        return saveFile(filepackage,path,file);
    }

    private Boolean saveFile(File filepackage, String path, MultipartFile file) {
        filepackage = new File(path);
        try {
            file.transferTo(filepackage);   //写入数据
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            SysConstant.isInsert = false;
            return  false;
        }
    }


    /**
     * 文件保存到数据库
     * @param fileData
     * @return
     */
    @RequestMapping("/addFile")
    @ResponseBody
    public Result addFile(FileData fileData){
        //System.out.println("add..=====================s");
        SysConstant.setFileData(fileData);
        //System.out.println("ceshi"+fileData.toString());

        //System.out.println("状态码:"+SysConstant.code);

        if (SysConstant.code == 200){
            return Result.success(200,"成功");
        }else {
            return Result.error(500,"失败");
        }
    }

    /**
     * 开关监听
     * @param checked
     */
    @RequestMapping("/switchTest")
    @ResponseBody
    public Result switchTest(FileData fileData,boolean checked){
        //System.out.println(checked);
        if (checked == true){
            fileData.setFileState("公开");
            return Result.success(0,"文件公开");
        }else {
            fileData.setFileState("未公开");
            return Result.success(0,"文件不公开");
        }
    }

    /**
     * 通过response获取一个输出流，将下载的文件写回浏览器端
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/download")
    @ResponseBody
    public Result download(@RequestParam(value = "fileId") Integer fileId, HttpServletRequest request,HttpServletResponse response){
        //System.out.println("文件id:"+fileId);
        //根据fileId查询要下载的文件
        FileData filedata = fileService.finFiledata(fileId);
        //被下载文件的url
        String fileUrl = filedata.getFileUrl();

        //获取要下载的文件名字
        String filename = filedata.getFileName();

        response.reset();

        if (filename != null){
            File file = new File(fileUrl,filename);    //根据文件地址和名字，获取文件对象
            //System.out.println(file);
            if (file.exists()){
                //System.out.println("cnm........");
                //设置文件ContentType类型，会自动判断下载文件类型
                String mimeType = request.getServletContext().getMimeType(filename);
                response.setContentType(mimeType);
                //设置文件是下载类型
                try {
                    response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"utf-8"));
                    response.setHeader("Pragma", "no-cache");
                    response.setHeader("Cache-Control", "no-cache");
                    response.setDateHeader("Expires", 0);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                response.setCharacterEncoding("utf-8");

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1){
                        //System.out.println(i);
                        os.write(buffer,0,i);
                        i = bis.read(buffer);
                    }
                    System.out.println("下载成功");

                    fis.close();
                    bis.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }else {
                return Result.error(500,"下载资源不存在");
            }
        }
        return Result.error(500,"文件下载失败");
    }

    @RequestMapping("/deleteFile")
    @ResponseBody
    public Result deleteFile(@RequestParam(value="deletelist[]")Integer[] deletelist){

        try {
            for (Integer fileId : deletelist) {

                FileData fileData = fileService.finFiledata(fileId);
                File file = new File(fileData.getFileUrl(),fileData.getFileName());

                if (file.isFile()){
                    //ystem.out.println("测试....");
                    file.delete();
                }
               fileService.deleteFileById(fileId);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.success(500,"删除失败");
        }
        return Result.success(200,"删除成功");
    }


    @RequestMapping("getFileTypeName")
    @ResponseBody
    public List<FileType> getFileTypeName(String fileTypeId){

        List<FileType> fileTypes = fileTypeService.findAll();
        return fileTypes;
    }

    @RequestMapping("/update")
    @ResponseBody
    public Result update(FileData fileData,boolean checked){

        //System.out.println("开关判断:"+checked);
        if (checked == true){
            fileData.setFileState("公开");
        }else{
            fileData.setFileState("未公开");
        }
        //System.out.println("要修改的数据："+fileData.toString());

        try {
            fileService.updateFile(fileData);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(500,"修改失败");
        }
        return Result.success(200,"修改成功");

    }
}
